﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

// SDD# - Software Defined Devices in C# for Linux and Windows
// Storage for station information (stream URLs)
// (c) 2014-2015 Chris Burri. MIT License applies. 
// See http://niston.wordpress.com

namespace sdd.subsystems.memory
{
    public class ProgramMemory
    {
        private Dictionary<int, Station> _Memory = new Dictionary<int, Station>();

        public void Add(int stationId, string URL)
        {
            var newProg = new Station(stationId, URL);
            if (_Memory.ContainsKey(stationId))
            {
                _Memory.Remove(stationId);
            }
            _Memory.Add(stationId, newProg);
        }

        public void Delete(int stationId)
        {
            if (_Memory.ContainsKey(stationId))
            {
                _Memory.Remove(stationId);
            }
        }


        public Station GetStation(int stationId)
        {
            if (_Memory.ContainsKey(stationId))
            {
                return _Memory[stationId];
            }
            else return null;
        }

        public Station GetStation(string stationUrl)
        {
            foreach (var x in _Memory)
            {
                if (x.Value.Url == stationUrl)
                {
                    return x.Value;
                }
            }
            return null;
        }

        public Station First
        {
            get
            {
                foreach (var x in _Memory)
                {
                    return x.Value;
                }
                return null;
            }
        }

        public Station GetNext(int currentId)
        {
            int nextId = 0;
            foreach (var x in _Memory)
            {
                if (x.Key > currentId)
                {
                    if (nextId == 0 | x.Key < nextId)
                    {
                        nextId = x.Key;
                    }
                }
            }
            if (nextId == 0) { nextId = _Memory.First().Key; }
            return _Memory[nextId];
        }

        public Station GetPrevious(int currentId)
        {
            int prevId = 0;
            foreach (var x in _Memory)
            {
                if (x.Key < currentId)
                {
                    if (prevId == 0 | x.Key > prevId )
                    {
                        prevId = x.Key;
                    }
                }
            }
            if (prevId == 0) { prevId = _Memory.Last().Key; }
            return _Memory[prevId];
        }

        
    }


}
